package br.com.klis.easycontrast;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import br.com.klis.easycontrast.filter.InputFilterMinMax;
import br.com.klis.easycontrast.model.Configuration;
import br.com.klis.easycontrast.model.Constants;
import br.com.klis.easycontrast.model.ContrastSession;
import br.com.klis.easycontrast.util.Validator;

/**
 * Formulario de configuracao da sessao de contraste
 * @author Inacio
 *
 */
public class MainActivity extends Activity {
	private static final String MIN_HOT_TIME = "1";
	private static final String MAX_HOT_TIME = "20";
	private static final String MIN_COLD_TIME = "1";
	private static final String MAX_COLD_TIME = "20";
	private static final String MIN_REPETITIONS = "1";
	private static final String MAX_REPETITIONS = "10";
	
	private static final String EASY_CONTRAST_PREFERENCES = "AppPreferences";
	private static final String PREFERENCE_COLD_TIME = "coldTime";
	private static final String PREFERENCE_HOT_TIME = "hotTime";
	private static final String PREFERENCE_REPETITIONS = "repetitions";
	private static final String PREFERENCE_STARTS_WITH = "startsWith";
	private static final String PREFERENCE_PLAY_SOUND = "playSound";
	private static final String PREFERENCE_VIBRATE = "vibrate";
	
	private EditText hotTimeEditText;
    private EditText coldTimeEditText;
    private EditText repetitionsEditText;
    private RadioButton startsHotRadioButton;
    private RadioButton startsColdRadioButton;
    private CheckBox playSoundCheckBox;
    private CheckBox vibrateCheckBox;
    private Button startSessionButton;
    private Configuration config;
    private ContrastSession session;
    
    private static final int MENU_ABOUT = 2;
   
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bindViewComponents();
        configureVIews();
        modelToView();
    }
    
    /**
     * Inicializa os objetos (views) do formulario
     */
    private void bindViewComponents(){
    	hotTimeEditText = (EditText) findViewById(R.id.hotTimeEditText);
        coldTimeEditText = (EditText) findViewById(R.id.coldTimeEditText);
        repetitionsEditText = (EditText) findViewById(R.id.repetitionsEditText);
        startsHotRadioButton = (RadioButton)findViewById(R.id.startsHotRadioButton);
        startsColdRadioButton = (RadioButton)findViewById(R.id.startsColdRadioButton);
        playSoundCheckBox = (CheckBox)findViewById(R.id.playSoundCheckBox);
        vibrateCheckBox = (CheckBox)findViewById(R.id.vibrateCheckBox);
        startSessionButton = (Button) findViewById(R.id.startSessionButton);
        startSessionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	if (!validate()){
            		return;
            	}
            	viewToModel();
            	saveModel();
            	startSession();
            }
        });
    }
    
    /**
     * Configura os objetos (views) do formulario
     */
    private void configureVIews(){
        hotTimeEditText.setFilters(new InputFilter[]{ new InputFilterMinMax(MIN_HOT_TIME, MAX_HOT_TIME)});
        coldTimeEditText.setFilters(new InputFilter[]{ new InputFilterMinMax(MIN_COLD_TIME, MAX_COLD_TIME)});
        repetitionsEditText.setFilters(new InputFilter[]{ new InputFilterMinMax(MIN_REPETITIONS, MAX_REPETITIONS)});
    }
    
    /**
     * Seta os valores do modelo no formulario
     */
    private void modelToView(){
    	loadModel();
    	hotTimeEditText.setText(Integer.valueOf(config.getHotTime()).toString());
        coldTimeEditText.setText(Integer.valueOf(config.getColdTime()).toString());
        repetitionsEditText.setText(Integer.valueOf(config.getRepetitions()).toString());
        if (config.getStartsWith() == Constants.STARTS_WITH_HOT){
        	startsHotRadioButton.setChecked(true);
        }else{
        	startsColdRadioButton.setChecked(true);
        }
        vibrateCheckBox.setChecked(config.isVibrate());
        playSoundCheckBox.setChecked(config.isPlaySound());
    }
    
    /**
     * Salva o modelo para o mecanismo de persistência escolhido
     * No caso, salvando o objeto de configuração nas preferências
     */
    private void saveModel() {
    	SharedPreferences preferences = getSharedPreferences(EASY_CONTRAST_PREFERENCES, MODE_PRIVATE);
    	SharedPreferences.Editor editor = preferences.edit();
    	editor.putInt(PREFERENCE_COLD_TIME, config.getColdTime());
    	editor.putInt(PREFERENCE_HOT_TIME, config.getHotTime());
    	editor.putInt(PREFERENCE_REPETITIONS, config.getRepetitions());
    	editor.putInt(PREFERENCE_STARTS_WITH, config.getStartsWith());
		editor.putBoolean(PREFERENCE_PLAY_SOUND, config.isPlaySound());
		editor.putBoolean(PREFERENCE_VIBRATE, config.isVibrate());
		editor.commit();
    }
    
    /**
     * Carrega os valores salvos para o modelo
     * No caso, carrega o objeto de configuração
     */
    private void loadModel() {
    	SharedPreferences preferences = getSharedPreferences(EASY_CONTRAST_PREFERENCES, MODE_PRIVATE);
    	config = new Configuration(
    			Integer.valueOf(preferences.getInt(PREFERENCE_HOT_TIME,Constants.DEFAULT_HOT_TIME)).toString(),
    			Integer.valueOf(preferences.getInt(PREFERENCE_COLD_TIME,Constants.DEFAULT_COLD_TIME)).toString(), 
    			Integer.valueOf(preferences.getInt(PREFERENCE_REPETITIONS, Constants.DEFAULT_REPETITIONS)).toString(),
    			preferences.getInt(PREFERENCE_STARTS_WITH, Constants.DEFAULT_STARTS_WITH),
    			preferences.getBoolean(PREFERENCE_PLAY_SOUND, Constants.DEFAULT_PLAY_SOUND),
    			preferences.getBoolean(PREFERENCE_VIBRATE, Constants.DEFAULT_VIBRATE));
    }
    
    /**
     * Valida os dados
     * @return true se dados ok, false se dados incorretos
     */
    private boolean validate(){
    	if(!Validator.validateNotNull(this, coldTimeEditText, R.string.validation_message_cold_time)){
    		return false;
    	}
    	if(!Validator.validateNotNull(this, hotTimeEditText, R.string.validation_message_hot_time)){
    		return false;
    	}
    	if(!Validator.validateNotNull(this, repetitionsEditText, R.string.validation_message_repetitions)){
    		return false;
    	}
    	return true;
    }
    
    /**
     * Seta os dados da view no modelo
     */
    private void viewToModel(){
    	String hotTime = hotTimeEditText.getText().toString();
    	String coldTime = coldTimeEditText.getText().toString();
    	String repetitions = repetitionsEditText.getText().toString();
    	
    	int startsWith = 0;
    	if(startsHotRadioButton.isChecked()){
        	startsWith = Constants.STARTS_WITH_HOT;
        }else if(startsColdRadioButton.isChecked()){
        	startsWith = Constants.STARTS_WITH_COLD;
        }
    	
    	boolean playSound = playSoundCheckBox.isChecked();
    	boolean vibrate = vibrateCheckBox.isChecked();
    	
    	if (config == null){
    		config = new Configuration(hotTime, coldTime, repetitions, startsWith, playSound, vibrate);	
    	}else{
    		config.setHotTime(hotTime);
    		config.setColdTime(coldTime);
    		config.setRepetitions(repetitions);
    		config.setStartsWith(startsWith);
    		config.setPlaySound(playSound);
    		config.setVibrate(vibrate);
    	}
    }
    
    /**
     * Inicia uma sessão a partir da configuração estabelecida
     */
    private void startSession(){
    	/*// para diminuir tempo de teste. em producao deve ficar comentado -----------

		config.setHotTime(0);
		config.setHotTimeSec(5);
		config.setColdTime(0);
		config.setColdTimeSec(5);
		
		// ---------------------------------------------------------------------------
*/		
    	session = new ContrastSession(config);
    	goTo();
    }
    
    /**
     * Vai para a tela de sessão de contraste passando o objeto sessão configurado
     */
    private void goTo(){
    	Intent myIntent = new Intent(getApplicationContext(), ContrastActivity.class);
    	myIntent.putExtra(Constants.CONTRAST_SESSION, session);
        startActivityForResult(myIntent, 0); //Cria uma tela filha
    }
    
    /**
     * Trata o resultado do retorno da tela filha
     * Se foi confirmada a saida da aplicação a partir da tela filha esta tela eh finalizada
     */
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    	super.onActivityResult(requestCode, resultCode, data); 
    	
    	if (resultCode == Activity.RESULT_OK) { 
    		String retorno = data.getStringExtra(Constants.SAIR_DA_APLICACAO);
    		if(retorno != null && retorno.equals("1")){
    			this.finish();
    		}
    	} 
    }
    
    /**
	 * Monta o menu da atividade
	 */
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, MENU_ABOUT, 0, R.string.about_title).setIcon(android.R.drawable.ic_menu_info_details);
    	return true;
    }
	
	/**
	 * Controla o item do menu selecionado
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if ( item.getItemId() == MENU_ABOUT ) {
    		showDialog(Constants.DIALOG_ABOUT);
    	} 
    	return true;
    }
    
    /**
	 * Controla a criacao das telas de dialogo
	 */
	@Override
    protected Dialog onCreateDialog(int id) {
    	Dialog d = null;
    	
    	//Dialogo About
    	if ( id == Constants.DIALOG_ABOUT ) {
    		d = DialogAbout.create(this,getApplicationContext(), LAYOUT_INFLATER_SERVICE);
    	}
    	
    	return d;
    }
}